<?php
/**
* @author moufer<moufer@163.com>
* @copyright (c)2001-2014 Moufersoft
* @website www.modoer.com
*/

!defined('IN_MUDDER') && exit('Access Denied');

/**
* 公众平台配置类
*/
class mc_weixin_custom_cmd extends ms_base
{

	//通过自定义指令ID来获取一条指令信息
	public static function read($id)
	{
		$custom_obj = _G('loader')->model('weixin:custom_cmd');
		$data = $custom_obj->read($id);
		if($data) return false;
		return new self($data);
	}

	//获取指定公众号的默认回复指令
	public static function read_default($mp_id)
	{
		$custom_obj = _G('loader')->model('weixin:custom_cmd');
		$data = $custom_obj->find_one('*', array('mp_id'=>$mp_id,'is_default'=>1));
		if(!$data) return false;
		return new self($data);
	}

	//获取指定公众号的关注回复指令
	public static function read_subscribe($mp_id)
	{
		$custom_obj = _G('loader')->model('weixin:custom_cmd');
		$data = $custom_obj->find_one('*', array('mp_id'=>$mp_id,'is_subscribe'=>1));
		if(!$data) return false;
		return new self($data);
	}

	//通过指定公众号和关键字查找指令
	public static function read_by_keyword($mp_id, $keyword)
	{
		$custom_obj = _G('loader')->model('weixin:custom_cmd');
		$data = $custom_obj->find_one('*', array('mp_id'=>$mp_id,'keyword'=>$keyword));
		if(!$data) return false;
		return new self($data);
	}

	public function __construct($data)
	{
		parent::__construct();
		foreach ($data as $key => $value) {
			$this->$key = $value;
		}
		if($this->msgtype == 'news') {
			$this->content = ms_mxml::to_array($this->content);
			if(!$this->content) $this->content = array();
		}
	}

	//回复微信用户
	public function reply($ToUserName, $FromUserName, $role_obj)
	{
		if($this->msgtype == 'news') {
			$reply_obj = mc_weixin_reply::factory('news');
			foreach ($this->content as $news) {
				$reply_obj->add_article($news['Title'], 
					$news['Description'], 
					S('siteurl').$news['PicUrl'], 
					str_replace(array('&nbsp;','&#38;'), '&', $news['Url'])
				);
			}
		} else {
			$reply_obj = mc_weixin_reply::factory('text');
			$reply_obj->set_content($this->content);
		}
		if($reply_obj->set_user($ToUserName, $FromUserName)->send($role_obj)) {
			$custom_obj = G('loader')->model('weixin:custom_cmd');
			$custom_obj->update_replys();
			return true;
		}
		return false;
	}

}

/** end **/